from flask import Flask, request, jsonify
from flask_cors import CORS
from flask_socketio import SocketIO, emit
import threading
from analysis_task import Analysis, Send

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 初始化 SocketIO
socketio = SocketIO(app, cors_allowed_origins="*")

# 存储当前运行的 Analysis 实例
current_analysis = None
analysis_lock = threading.Lock()

@app.route('/')
def hello_world():
    return 'Hello, World!'


@app.route('/capture', methods=['POST'])
def receive_capture_condition():
    global current_analysis
    # 获取前端发送的 JSON 数据
    data = request.get_json()

    # 提取帧数量和捕获条件
    frame_count = data.get('frameCount')
    capture_condition = data.get('captureCondition')

    # 在原来的示例上继续捕获
    with analysis_lock:
        print(f"\n\n\n当前运行的是：{current_analysis}\n\n\n")
        if current_analysis is None : current_analysis = Analysis.Analysis(frame_count, capture_condition)
        else :
            current_analysis.refresh(frame_count,capture_condition)
        if current_analysis.sniffFlag:
            current_analysis.start_sniff()
    return jsonify({
        'status': 'success',
        'message': '开始捕获数据'
    }), 200


@app.route('/clear_data', methods=['POST'])
def clear_data():
    global current_analysis
    with analysis_lock:
        if current_analysis is not None:
            print(current_analysis.listbox)
            # 调用 Analysis 实例的清理方法
            current_analysis.clear_data()
            return jsonify({
                'status': 'success',
                'message': '数据已清理'
            }), 200
        else: 
            return jsonify({
                'status': 'error',
                'message': '没有正在运行的捕获任务'
            }), 400


@app.route('/current_data', methods=['GET'])
def get_current_data():
    global current_analysis
    with analysis_lock:
        if current_analysis is not None:
            # 返回当前捕获的数据
            return jsonify({
                'status': 'success',
                'data': current_analysis.listbox,
                'packet_count': current_analysis.countAct
            }), 200
        else:
            return jsonify({
                'status': 'success',
                'data': [],
                'packet_count': 0
            }), 220

# 停止捕获方法
@app.route('/stop_capture', methods=['POST'])
def stop_capture():
    global current_analysis
    with analysis_lock:
        if current_analysis is not None and not current_analysis.sniffFlag :
            print("\n\n\n停止捕获\n\n\n")
            # 调用 Analysis 停止捕获方法
            current_analysis.stop_sniff()
            return jsonify({
                'status': 'success',
                'message': '捕获已停止'
            }), 200
        else:
            return jsonify({
                'status': 'error',
                'message': '没有正在运行的捕获任务'
            }), 400

# 查看数据方法
@app.route("/view_data",methods = ['POST'])
def view_data():
    global current_analysis
    data = request.get_json()
    index = data.get('index')
    if current_analysis is None:
        return jsonify({
            'status': 'error',
            'message': '没有正在运行的捕获任务'
        }), 400
    try:
        current_analysis.choosedPDUAnalysis(index)
        return jsonify({
            'status': 'success',
            'data': current_analysis.current_packet,
            'hex_dump': current_analysis.hexadecimal_dump
        }), 200
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

# 发送MAC帧
@app.route("/send_mac",methods = ['POST'])
def send_mac():
    print("开始发送MAC帧")
    data = request.get_json()['formData']
    # 转换MAC地址格式：将连字符替换为冒号
    if '-' in data['dstMac']:
        data['dstMac'] = data['dstMac'].replace('-', ':')
    print(data)
    try:
        result_text = Send.send_mac(
            data['dstMac'],
            data['payload'],
            int(data['count'])
        )
        return jsonify({
            'status': 'success',
            'message': '发送成功',
            'data' : result_text
        }),200
    except ValueError:
        print("发送次数必须是有效的数字!")
        return jsonify({
            'status': 'error',
            'message': '发送次数必须是有效的数字!'
        }),400
    except Exception as e:
        print("发送过程中发生错误:", e)
        return jsonify({
            'status': 'error',
            'message': f"发送过程中发生错误: {str(e)}"
        }),500


# 发送ARP包
@app.route("/send_arp",methods = ['POST'])
def send_arp():
    print("开始发送ARP包")
    data = request.get_json()['formData']
    # 转换MAC地址格式：将连字符替换为冒号
    if '-' in data['dstMac']:
        data['dstMac'] = data['dstMac'].replace('-', ':')
    print(data)
    try:
        result_text = Send.send_arp(
            data['dstMac'],
            data['dstIp'],
            data['payload'],
            int(data['count']),
            data['networkType'],
            data['protocolType'],
            data['arpOp']
        )
        return jsonify({
            'status': 'success',
            'message': '发送成功',
            'data' : result_text
        }),200
    except ValueError:
        print("发送次数必须是有效的数字!")
        return jsonify({
            'status': 'error',
            'message': '发送次数必须是有效的数字!'
        }),400
    except Exception as e:
        print("发送过程中发生错误:", e)
        return jsonify({
            'status': 'error',
            'message': f"发送过程中发生错误: {str(e)}"
        }),500

#  发送IP报
@app.route("/send_ip",methods = ['POST'])
def send_ip():
    print("开始发送IP包")
    data = request.get_json()['formData']
    print(data)
    try:
        result_text = Send.send_ip(
            data['dstIp'],
            data['srcIp'],
            data['payload'],
            int(data['count']),
            data['ipVersion'],
        )
        return jsonify({
            'status': 'success',
            'message': '发送成功',
            'data' : result_text
        }),200
    except ValueError:
        print("发送次数必须是有效的数字!")
        return jsonify({
            'status': 'error',
            'message': '发送次数必须是有效的数字!'
        }),400
    except Exception as e:
        print("发送过程中发生错误:", e)
        return jsonify({
            'status': 'error',
            'message': f"发送过程中发生错误: {str(e)}"
        }),500

# 发送TCP数据包
@app.route("/send_tcp",methods = ['POST'])
def send_tcp():
    print("开始发送TCP包")
    data = request.get_json()['formData']
    print(data)
    try:
        result_text = Send.send_tcp(
            data['dstIp'],
            data['srcIp'],
            data['payload'],
            int(data['count']),
            data['ipVersion'],
            int(data['dstPort']),
            int(data['srcPort']),
            int(data['windowSize']),
            int(data['seqNum']),
            int(data['ackNum']),
            data['urg'],
            data['ack'],
            data['psh'],
            data['rst'],
            data['syn'],
            data['fin']
        )
        return jsonify({
            'status': 'success',
            'message': '发送成功',
            'data' : result_text
        }),200
    except ValueError:
        print("发送次数必须是有效的数字!")
        return jsonify({
            'status': 'error',
            'message': '发送次数必须是有效的数字!'
        }),400
    except Exception as e:
        print("发送过程中发生错误:", e)
        return jsonify({
            'status': 'error',
            'message': f"发送过程中发生错误: {str(e)}"
        }),500

# 发送UDP数据包
@app.route("/send_udp",methods = ['POST'])
def send_udp():
    print("开始发送UDP包")
    data = request.get_json()['formData']
    print(data)
    try:
        result_text = Send.send_udp(
            data['dstIp'],
            data['srcIp'],
            data['payload'],
            int(data['count']),
            data['ipVersion'],
            int(data['dstPort']),
            int(data['srcPort'])
        )
        return jsonify({
            'status': 'success',
            'message': '发送成功',
            'data' : result_text
        }),200
    except ValueError:
        print("发送次数必须是有效的数字!")
        return jsonify({
            'status': 'error',
            'message': '发送次数必须是有效的数字!'
        }),400
    except Exception as e:
        print("发送过程中发生错误:", e)
        return jsonify({
            'status': 'error',
            'message': f"发送过程中发生错误: {str(e)}"
        }),500

if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1')
